package git.soulbgm.service.impl;

import git.soulbgm.common.Constant;
import git.soulbgm.config.SysConfig;
import git.soulbgm.handler.TcpSimpleHandle;
import git.soulbgm.listener.ConnectionListener;
import git.soulbgm.pojo.BaseMsg;
import git.soulbgm.service.TcpServer;
import git.soulbgm.utils.ByteUtil;
import git.soulbgm.utils.SerializeUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author 贺瑞杰
 * @version V1.0
 * @date 2018-10-17 11:06
 * @description
 */
@Service
@Slf4j
public class TcpServerImpl implements TcpServer, Runnable {

    /**
     * 管理连接线程组
     */
    private EventLoopGroup boosGroup;

    /**
     * 管理传输数据线程组
     */
    private EventLoopGroup workGroup;

    @Autowired
    private TcpSimpleHandle handle;

    @Autowired
    private SysConfig config;

    /**
     * 传输管道
     */
    private Channel channel;

    private ThreadPoolExecutor threadPool;

    private ServerBootstrap bootstrap;

    private static final byte[] TCP_DELIMITER;

    static {
        TCP_DELIMITER = "$_$".getBytes();
    }

    @PostConstruct
    public void init() {
        ThreadFactory threadFactory = new DefaultThreadFactory("tcpClient");
        threadPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1024), threadFactory, new ThreadPoolExecutor.AbortPolicy());
        threadPool.execute(this);
    }

    @Override
    public void run() {
        boosGroup = new NioEventLoopGroup(config.getTcpBossThreadNumber());
        workGroup = new NioEventLoopGroup(config.getTcpWorkerThreadNumber());
        bootstrap = new ServerBootstrap()
                .group(boosGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(config.getTcpPort()))
                // 保持长连接
                .childOption(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive())
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline()
                                /*
                                    第一个参数 60 表示读操作空闲时间
                                    第二个参数 20 表示写操作空闲时间
                                    第三个参数 60*10 表示读写操作空闲时间
                                    第四个参数 单位/秒
                                 */
//                                .addLast(new IdleStateHandler(60, 20, 60 * 10, TimeUnit.SECONDS))
                                .addLast(new DelimiterBasedFrameDecoder(2048, ByteUtil.byteArrayToByteBuf(ByteUtil.stringToByteArray(Constant.TCP_DELIMITER))))
                                .addLast(handle)
                                .addLast(new StringEncoder());
                    }
                });
        doConnect();
    }

    @Override
    public void doConnect() {
        if (channel != null && channel.isActive()) {
            return;
        }
        try {
            ChannelFuture future = bootstrap.bind(config.getTcpPort()).sync();
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        channel = future.channel();
                        log.info("开启TCP服务端成功");
                    }
                }
            });
            channel = future.channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    @PreDestroy
    public void destroy() {
        boosGroup.shutdownGracefully().syncUninterruptibly();
        workGroup.shutdownGracefully().syncUninterruptibly();
        threadPool.shutdown();
        log.info("关闭TCP服务成功");
    }

    @Override
    public boolean sendMsg(BaseMsg msg) {
        if (msg == null) {
            return false;
        }
        byte[] data = null;
        while (channel == null) {

        }
        data = SerializeUtil.serializer(msg);
        data = ByteUtil.byteMergerAll(data, ByteUtil.stringToByteArray(Constant.TCP_DELIMITER));
        channel.writeAndFlush(ByteUtil.byteArrayToByteBuf(data));
        return true;
    }

}
